<template>
    <view class='content'> 
        <!-- #ifdef MP-WEIXIN -->
        <top-nav :inner-title="title" is-show-back="true" is-fixed="true" :navH="navH" :n="n" is-white="bg-white" opacity="1"></top-nav>
        <view  :style="{height:navH + 'px'}"></view>
        <!-- #endif -->
      <view class='item'>
        <view class='bar'>
          <view class='text'>联系人:</view>
          <view class='area b1'>
            <input class="input" :value='name' @input='nameEvent' placeholder='姓名' maxlength='10' type='text'></input>
          </view>
        </view>
        <view class='bar b1'>
          <view class='sex' @click='sexEvent(1)'>
            <view :class='sex == 1?"ck":""' class="icon"></view>
            <view class='sex-text'>男同学</view>
          </view>
          <view class='sex' @click='sexEvent(2)'>
            <view :class='sex == 2?"ck":""' class="icon"></view>
            <view class='sex-text'>女同学</view>
          </view>
        </view>
        <view class='bar'>
          <view class='text'>电话:</view>
          <view class='area'>
            <input class="input" :value='phone' @input='phoneEvent' placeholder='请填写收货手机号码' maxlength='11' type='number'></input>
          </view>
        </view>
        <view class='bar'>
          <view class='text' style="width:230rpx;">
            <view class="spare_number">备用联系电话:</view>
            <view class="tips_question" @click="showTip"></view>
          </view>
          <view class='area' style="margin-left:20rpx;">
            <input class="input" :value='bakPhone' @input='bakPhoneEvent' placeholder='请填写舍友手机号码' maxlength='11' type='number'></input>
          </view>
        </view>
      </view>
      <view class='item'>
        <view class='bar b1'>
            <view class='sex' @click='schoolEvent(1)'>
                <view :class='schoolType == 1?"ck":""' class="icon"></view>
                <view class='sex-text'>校内</view>
            </view>
            <view class='sex' @click='schoolEvent(2)'>
                <view :class='schoolType == 2?"ck":""' class="icon"></view>
                <view class='sex-text'>校外</view>
            </view>
        </view>
        <block v-if='schoolType == 1'>
            <view class='bar'>
                <view class='text'>学校:</view>
                <view class='area b1 select' @click="selectCity()">
                      <input class="input" disabled :value='schoolName' @input='schoolNameEvent' placeholder='选择学校' maxlength='15' type='text' v-if="!schoolName"></input>
                      <view class="input" v-else>{{schoolName}}</view>
                      <icon class="arr_right"></icon>
                </view>
            </view>
            <cascade-box class="cascade-box" :animationData="animationData" :prov="prov" :city="city" :school="school" 
                :column1="1" :column2="1" :column3="2.5" @cascadeCancel="cancelEvent()" @cascadeEnter="enterEvent" @cascadeChange="bindChange()"></cascade-box>
            <view class='bar'>
                <view class='text'>楼号:</view>
                <view class='area select' @click="selectNum">
                    <input class="input" disabled :value='addrName' @input='addrEvent' placeholder='例：学生宿舍9号楼' maxlength='15' type='text' v-if="!addrName"></input>
                    <view class="input" v-else>{{addrName}}</view>
                    <icon class="arr_right"></icon>
                </view>
            </view>
             <cascade-box class="cascade-box" :animationData="animationNumData" :prov="a1" :school="a2" :column1="2" :column2="0" :column3="2"
             @cascadeCancel="cancelNumEvent()" @cascadeEnter="enterNumEvent()" @cascadeChange="bindNumChange()"></cascade-box>


         <!-- <view class="cascade_box" :animation="animationNumData">
            <view class="cascade_hei"></view> 
            <view class="cascade_find">
              <view class="cascade_header">
                    <text class='quxiao' @click="cancelNumEvent()">取消</text>
                    <text class="queren" @click="enterNumEvent()">确认</text>
              </view>
              <picker-view indicator-style="height: 80rpx;" style="width: 100%; height: 400rpx;" @change="bindNumChange()">
                    <picker-view-column>   
                          <view v-for="(item,index) in a1" :key='index' style="line-height: 80rpx;text-align:center;">{{item}}
                          </view>
                    </picker-view-column>
                    <picker-view-column>
                          <view v-for="(item,index) in a2" :key='index' style="line-height: 80rpx;text-align:center;">{{item}}
                          </view>
                    </picker-view-column>
              </picker-view>
            </view>
          </view>    -->

            <view class='bar'>
                <view class='text'>宿舍号:</view>
                <view class='area'>
                    <input class="input" :value='Num' @input='numEvent' placeholder='例：520室' maxlength='15' type='text'></input>
                </view>
            </view>
        </block>
        <block v-else>
          <view class='bar'>
            <view class='text'>地址:</view>
            <view class='area'>
              <input class="input" :value='addrName' @input='addrEvent' placeholder='输入收货地址' maxlength='15' type='text'></input>
            </view>
          </view>
          <view class='bar'>
            <view class='text'>门牌号:</view>
            <view class='area'>
              <input class="input" :value='Num' @input='numEvent' placeholder='例：9号楼520室' maxlength='15' type='text'></input>
            </view>
          </view>
        </block>
      </view>
      <view class='save'>
        <block v-if='id != 0'>
            <button @click='deleteAddress()' class="delete-btn">删除</button>
        </block>
        
        <button @click='save()' class='save-btn'>保存</button>
      </view>
     </view>
</template>

<script>
	import uniFly from 'unifly';
	import request from '@/common/request.js';
	import $api_base from '@/api/api_base.js';
    import cascadeBox from '@/template/cascade/index.vue';
	import topNav from '@/template/topnav/index.vue';
	import event from '@/common/event.js';
	export default {
		components: { topNav,cascadeBox},
		data() {
			return {
				id: 0,
				name: '',
				sex: 1,
				phone: '',
				bakPhone: '',
				schoolType: 1,
				schoolName: '',
				addrName: '',
				Num: '',
				isSubmit: true,
				isDelete: true,
				prov: [],
				city: [],
				school: [],
				school_list: [],
				prov_index: 0,
				city_index: 0,
				school_index: 0,
				animationData: {},
				animationNumData: {},
				isCk: false,
				selectRegion: {},
				selectSchoolId: 0,
				provId: 0,
				cityId: 0,
				schoolId: 0,
				addrInfo: [],
				a1: [],
				a2: [],
                selectNumRegion: {},
				a1_index: 0,
				a2_index: 0,
				isNumCk: false,
				addrData: [],
				addrList: [],
				navH:0,
				n:0,
				title:''
			}
		},
		onLoad: function(options){
				var id = options.id || 0;
				var title = "";
				var self = this;
				if (!getApp().globalData.schoolList || getApp().globalData.schoolList.length==0) {
					// $api.HttpService({ long_lat: getApp().longLat }).then(function(res){
                    $api_base.post($api_base.homeIndex,{long_lat: getApp().longLat},1).then(function(res) {
						let data = res.data;
						if (data.ok == 1 || data.ok == 2) {
							getApp().globalData.schoolInfo = data.schoolInfo;
							getApp().globalData.userInfo = data.userInfo;
							getApp().globalData.schoolList = data.schoolList;
							getApp().kfPhone = data.kfPhone;
							self.listEvent(getApp().globalData.schoolList);
						}
					});
				}else{
                    console.log(getApp().globalData.schoolList);
					self.listEvent(getApp().globalData.schoolList);
				}
				if (id > 0) {
					$api_base.post($api_base.getAddressByid,{ id: id }).then(function(e){
                        console.log(e);
						var data = e.data.data;
						self.name 		= data.name, 
						self.sex 		= data.sex,
						self.phone 		= data.phone, 
						self.bakPhone 	= data.bak_phone,
						self.provId 	= data.prov_id, 
						self.cityId 	= data.city_id,
						self.schoolId 	= data.school_id, 
						self.schoolType = data.school_type, 
						self.schoolName = data.school_name,
						self.addrName 	= data.addr_name,
						self.Num 		= data.num,
						self.addrInfo 	= e.data.addr_info, 
						self.addrData 	= e.data.addr_info
					   // self.loadData();
					});
					title = "编辑收货地址";
				}else{
					title = "新增收货地址";
				}
				this.navH  = getApp().globalData.navHeight;
                this.n     = getApp().globalData.n;
				this.title = title;
				this.id    = id;
		 },
		 methods:{
			//加载宿舍
			loadData: function () {
				var self = this;
				$api_base.post($api_base.getNumList,{ school_id: this.schoolId }).then(function(data){
					let e = data.data;
					if (e.ok == 1) {
						self.addrList = e.addr_list;
						self.numLoadData(e.addr_list);
					}
				});
			},
			//输入事件
			nameEvent: function (e) {
				this.name = e.target.value;
			},
			sexEvent: function (e) {
				this.sex = e;
			},
			phoneEvent: function (e) {
				this.phone= e.target.value
			},
			bakPhoneEvent: function (e) {
				this.bakPhone = e.target.value;
			},
			schoolEvent: function (e) {
				this.schoolType = e; 
				this.addrName 	= '';
				this.Num		= '';
			},
			schoolNameEvent: function (e) {
                
				this.schoolName = e.target.value
			},
			addrEvent: function (e) {
				this.addrName = e.target.value;
			},
			numEvent: function (e) {
				this.Num  = e.target.value;
			},
			//宿舍
			selectNum: function () {
				if (this.schoolId <= 0) {
					uni.showToast({title: '请先选择学校', icon: "none"});
					return false;
				}
				if (this.addrList.length < 0) return false;
				this.loadData();
				var animation = uni.createAnimation({
					duration: 300,
					timingFunction: 'ease',
				});
				animation.height(1322 + 'rpx').step();
				this.animationNumData = animation.export();
				this.isNumCk = true;
			},
			bindNumChange: function (e) {
				const val = e.detail.value;
				this.a1_index = val[0];
				this.a2_index = val[2];
				this.numLoadData(this.addrList);
			},
			enterNumEvent: function () {    //确认选中楼号
				var animation = uni.createAnimation({
					duration: 500,
					timingFunction: 'ease',
				});
				animation.height(0 + 'rpx').step();
				var selectData = this.addrList[this.a1_index].regions[this.a2_index];
				this.addrName		  = selectData.name;
				this.addrData		  = selectData;
				this.animationNumData = animation.export();
				this.isNumCk		  = false;
			},
			cancelNumEvent: function () {
				var animation = uni.createAnimation({
					duration: 500,
					timingFunction: 'ease',
				});
				animation.height(0 + 'rpx').step();
				this.animationNumData = animation.export();
				this.isNumCk = false;
			},
			numLoadData: function (allData) {
				if (allData.length <= 0) return false;
				var self = this;
				var a1 = [];
				var a2 = [];
				var a1_index = self.a1_index;
				var a2_index = self.a2_index;
				for (let i = 0; i < allData.length; i++) {
					a1.push(allData[i].name)
				}
				if (allData[a1_index].regions) {
					if (allData[a1_index].regions[a2_index]) {
						for (let i = 0; i < allData[a1_index].regions.length; i++) {
							a2.push(allData[a1_index].regions[i].name);
						}
					}
				} else {
					a2.push(allData[a1_index].name);
				}
				self.a1 = a1;
				self.a2 = a2;
				self.selectNumRegion = {
                    a1: a1[self.a1_index],
                    a2: a2[self.a2_index]
                };
			},
			//联动相关
			selectCity: function () {
				var animation = uni.createAnimation({
					duration: 300,
					timingFunction: 'ease',
				})
				animation.height(1332 + 'rpx').step();
				this.animationData = animation.export();
				this.isCk = true;
			},
			listEvent: function (allData) {
				var self = this;
				var prov = [];
				var city = [];
				var school = [];
				var school_list = [];
				var city_index = self.city_index;
				var prov_index = self.prov_index;
				var school_index = self.school_index;
				var str_func = function (e) {
					if (e.substr(-1, 1) == '市') {
						e = e.substr(0, e.length - 1);
					}
					return e;
				};
				for (let i = 0; i < allData.length; i++) {
					prov.push(allData[i].name)
				}
				if (allData[prov_index].regions) {
					if (allData[prov_index].regions[city_index]) {
						for (let i = 0; i < allData[prov_index].regions.length; i++) {
							city.push(str_func(allData[prov_index].regions[i].name));
						}
						if (allData[prov_index].regions[city_index].regions) {
							for (let i = 0; i < allData[prov_index].regions[city_index].regions.length;
								 i++) {
								school.push(str_func(allData[prov_index].regions[city_index].regions[i].name));
								school_list.push(allData[prov_index].regions[city_index].regions[i].id);
							}
						}
					}
				} else {
					city.push(str_func(allData[prov_index].name));   
				}
				self.prov		 = prov;
				self.city		 = city; 
				self.school 	 = school;
				self.school_list = school_list;
				if (prov.length == 0 || city.length == 0) {
					self.listEvent(getApp().globalData.schoolList);
				}
				self.selectRegion   = {
                    prov: prov[self.prov_index],
                    city: city[self.city_index],
                    school: school[self.school_index]
                 };
				self.selectSchoolId = school_list[self.school_index];
			},
			bindChange: function (e) {
				const val = e.detail.value;
				this.prov_index	  = val[0];
				this.city_index	  = val[1];
				this.school_index = val[2];
				this.listEvent(getApp().globalData.schoolList);
			},
			enterEvent: function () {
				var animation = uni.createAnimation({
					duration: 500,
					timingFunction: 'ease',
				});
				var selectData = this.selectRegion;
				animation.height(0 + 'rpx').step();
				if (this.selectSchoolId !== this.schoolId) {
					this.addrData = [];
					this.addrName = '';
				}
				this.animationData = animation.export();
				this.schoolId	   = this.selectSchoolId;
				this.schoolName	   = selectData.school;
				this.addrList      = [];
			  //  this.loadData();
			},
			showTip: function(){
				uni.showModal({
					title: '',
					content: '如收货电话未接通，骑手将通过备用联系电话联系收货人',
					showCancel: false,
					confirmText: '知道了',
					confirmColor: '#12D195',
					success(res) {
						if (res.confirm) {
							console.log('用户点击确定')
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})
			},
			cancelEvent: function () {
				var animation = uni.createAnimation({
					duration: 500,
					timingFunction: 'ease',
				});
				animation.height(0 + 'rpx').step();
				this.animationData = animation.export();
				this.isCk		   = false;
				this.selectRegion = {};
			},
            save: function () {
                var id         = this.id;
                var name       = this.name;
                var sex        = this.sex;
                var phone      = this.phone;
                var bakPhone   = this.bakPhone;
                var schoolType = this.schoolType;
                var schoolId   = this.schoolId;
                var schoolName = this.schoolName;
                var addrData   = this.addrData || [];
                var addrName   = this.addrName;
                var Num        = this.Num;
                var self       = this;
                if (!this.isSubmit) {
                    return false;
                }
                if (name == '') {
                    uni.showToast({title: '请输入联系人', icon: "none"});
                    return false;
                }
                if (phone == '') {
                    uni.showToast({title: '请输入手机号码', icon: "none"});
                    return false;
                }
                if (bakPhone == '') {
                    uni.showToast({title: '请输入备用手机号码', icon: "none"});
                    return false;
                }
				// if (bakPhone == phone) {
				//     uni.showToast({title: '备用手机号码不能与手机号一致', icon: "none"});
				//     return false;
				// }
				if (bakPhone.length != 11) {
				    uni.showToast({title: '备用手机号码格式不正确', icon: "none"});
				    return false;
				}
                if (schoolType == 1 && schoolName == '') {
                    uni.showToast({title: '请选择学校', icon: "none"});
                    return false;
                }
                if (schoolType == 1 && addrName == '') {
                    uni.showToast({title: '请选择楼栋', icon: "none"});
                    return false;
                }
                if (schoolType == 1 && Num == '') {
                    uni.showToast({title: '请输入宿舍号', icon: "none"});
                    return false;
                }
                if (schoolType == 2 && addrName == '') {
                    uni.showToast({title: '请输入地址', icon: "none"});
                    return false;
                }
                if (schoolType == 2 && Num == '') {
                    uni.showToast({title: '请输入门牌号', icon: "none"});
                    return false;
                }
                var where = new Object();
                where.id = id; where.name = name; where.sex = sex; where.phone = phone; where.bakPhone = bakPhone; where.school_type = schoolType;
                where.school_id = schoolId; where.addr_name =  addrName; where.addr_id = addrData.id; where.num = Num;

                this.isSubmit = false;
                $api_base.post($api_base.saveAddress, where ).then(function(e){
                    let data = e.data;
                    self.isSubmit = true;
                    if (data.ok == 1) {
                        uni.showToast({title: data.msg, icon: "none"});
                        setTimeout(function () {
                            uni.navigateBack();
                        }, 2000);
                    } else {
                        uni.showToast({title: data.msg, icon: "none"});
                    }
                });
            },
            deleteAddress: function (e) {
                var self = this;
                self.isDelete = false;
                var uid = uni.getStorageSync('openid');
                var id  = self.id;
                 $api_base.post($api_base.deleteAddress, {id:id,uid:uid} ).then(function(e){
                    let data = e.data;
                    self.isSubmit = true;
                    if (data.ok == 1) {
                        uni.showToast({title: '删除成功', icon: "none"});
                        setTimeout(function () {
                            uni.navigateBack();
                        }, 1000);
                    } else {
                        uni.showToast({title: data.msg, icon: "none"});
                    }
                });
            },
		 }
	}
</script>
<style>
  page {
  background-color: #fff;
  }
</style>
<style lang="scss" scoped>
	@import 'index.scss';
</style>
